/*******************************************************************************
 * Copyright (c) 2010 liw.
 * All rights reserved. 
 * 
 * This file is part of VanBus.
 * 
 *     VanBus is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     VanBus is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with VanBus.  If not, see <http://www.gnu.org/licenses/>.
 * Contributors:
 *     liw - initial API and implementation
 ******************************************************************************/
package org.niclab.vanbus.application;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.codehaus.jackson.JsonFactory;
import org.niclab.vanbus.database.ApplicationDataBase;
import org.niclab.vanbus.gps.MyLocationManager;
import org.niclab.vanbus.preference.AppPreferences;

import android.app.Application;
import android.database.sqlite.SQLiteOpenHelper;
import android.preference.Preference;
import android.util.Log;

public class VanBusApplication extends Application{
	
	static private String LOG_TAG=VanBusApplication.class.getSimpleName();
	private HttpClient httpClient;
	private ScheduledExecutorService scheduledExecutorService;
	private JsonFactory jsonFactory;
	private AppPreferences preferences;
	private MyLocationManager myLocationManager;
	private HashMap<String, SoftReference> dataCache;//for caching data around
	private HashMap<String,Object> tempData;//temp data for passing around

	private static VanBusApplication instance;

	
	//globally shared data
	//public static final String BUS_ROUTE_LIST="BUS_ROUTE_LIST";
	//public static final String SELECTED_BUS_ROUTE="SELECTED_BUS_ROUTE";
	
	@Override
	public void onCreate(){
		
		super.onCreate();
		httpClient=createHttpClient();
		jsonFactory = createJsonFactory();
		preferences = createPreferences();
		dataCache = new HashMap<String,SoftReference>();
		tempData = new HashMap<String,Object>();
		scheduledExecutorService = Executors.newScheduledThreadPool(2);
		myLocationManager = new MyLocationManager(this);

	
		instance = this;
		Log.d(LOG_TAG,"Application onCreate() done.");
		
	}

	static public VanBusApplication getInstance(){
		return instance;
		
	}
	
	public ScheduledExecutorService getScheduledExecutorService(){
		return scheduledExecutorService;
	}
	
	public MyLocationManager getMyLocationManager(){
		return myLocationManager;
	}
	
	private AppPreferences createPreferences() {
		AppPreferences prefs= new AppPreferences(this);
		return prefs;
	}

	public AppPreferences getPreferences(){
		return preferences;
	}

	
	private JsonFactory createJsonFactory() {
		return new JsonFactory();
	}


	public JsonFactory getJsonFactory(){
		return jsonFactory;
	}
	
	@Override
	public void onLowMemory(){
		
		super.onLowMemory();
		closeHttpClient();
	}
	
	
	@Override
	public void onTerminate(){
		
		super.onTerminate();
		closeHttpClient();
		scheduledExecutorService.shutdownNow();
	}
	
	public Object putToCache(String key, Object obj){
		
		SoftReference wObj = new SoftReference(obj);
		SoftReference sf = dataCache.put(key, wObj);
		return (sf==null)?null:sf.get();
		
	}
	
	public Object fetchFromCache(String key){
		SoftReference sf;
		if( (sf = dataCache.get(key))==null)
			return null;
		return sf.get();
	}
	
	public void saveTempData(String key, Object value){
		tempData.put(key, value);
	}
	
	public Object getAndRemoveTempData(String key){
		
		return tempData.remove(key);
	}
	//it clears the data at the same time
	public void cleanTempData(String key){
		tempData.remove(key);
		
	}
	
	public HttpClient getHttpClient(){
		
		return httpClient;
		
	}

	private HttpClient createHttpClient(){
		
		Log.d(LOG_TAG,"createHttpClient()...");
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
		HttpProtocolParams.setUseExpectContinue(params, true);
	
		HttpConnectionParams.setConnectionTimeout(params, 10*1000);
		HttpConnectionParams.setSoTimeout(params, 10*1000);
		
		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		schReg.register(new Scheme("https",SSLSocketFactory.getSocketFactory(), 443));
		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params,schReg);
		return new DefaultHttpClient(conMgr, params);
		
	}
	
	private void closeHttpClient(){
		
		if(httpClient!=null && httpClient.getConnectionManager()!=null)
		{
			httpClient.getConnectionManager().shutdown();
		}
	} 
	
}
